package com.ld.hpfs.service.impl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.dao.EnterInvoiceMapper;
import com.ld.hpfs.pojo.Exp;
import com.ld.hpfs.pojo.Invoice;
import com.ld.hpfs.pojo.Transport;
import com.ld.hpfs.service.EnterInvoiceService;

@Service
public class EnterInvoiceServiceImpl implements EnterInvoiceService{
	
	private static final Logger logger = LoggerFactory.getLogger(DealServiceImpl.class);
	
	@Autowired
	private EnterInvoiceMapper enterInvoiceMapper;
	
	@Autowired  
    private JdbcTemplate jdbcTemplate;  
	
	/*
	 * 获取票据号
	 * @see com.ld.hpfs.service.EnterInvoiceService#getInvoiceCode(java.util.HashMap)
	 */
	@Override
	public HashMap<String,Object> getInvoiceCode(HashMap<String,Object> param){
//		HashMap<String,Object> code = new HashMap<String,Object>();
//		code.put("code", "001");
//		return code;
		final int company_id = (Integer)param.get("company_id");
		HashMap<String,Object> result = new HashMap<String,Object>();
		try{
			String param2Value = (String)jdbcTemplate.execute(   
			     new CallableStatementCreator() {   
			        public CallableStatement createCallableStatement(Connection con) throws SQLException {   
			           String storedProc = "{call sp_tax_get_docno(?,?)}";// 调用的sql   
			           CallableStatement cs = con.prepareCall(storedProc);   
			           cs.setInt(1, company_id);// 设置输入参数的值   
			           cs.registerOutParameter(2, Types.VARCHAR);// 注册输出参数的类型   
			           return cs;   
			        }   
			     }, new CallableStatementCallback() {   
			         public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {   
			           cs.execute();   
			           return cs.getString(2);// 获取输出参数的值   
			     }   
		    });
		//	result = enterInvoiceMapper.getVoucherOperater(company_id);
			result.put("code", param2Value);  
			return result;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}
	
	/*
	 * 获取grid信息
	 * @see com.ld.hpfs.service.EnterInvoiceService#getInvoiceDetailList(java.util.HashMap)
	 */
	@Override
	public ArrayList<HashMap<String,Object>> getInvoiceDetailList(HashMap<String,Object> param){
		try{	
			ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
		    String type = enterInvoiceMapper.getTypeFromHead(param);
		 	if(type.equals("T_INV")){
		 	    result = enterInvoiceMapper.getTransInvoiceDetailList(param);
		 	 }else{
		 		 result = enterInvoiceMapper.getInvoiceDetailList(param); 
		 	 }
			return result;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}
	
	/*
	 * 获取单据信息
	 */
	@Override
	public ArrayList<HashMap<String,Object>> getInvoiceMainList(HashMap<String,Object> param){
		try{
			ArrayList<HashMap<String,Object>> list = enterInvoiceMapper.getInvoiceMainList(param);
			if(!list.isEmpty()){
				String type = list.get(0).get("DOC_TYPE_CODE").toString();
				if(type.equals("E_INV")){//获取进出口发票信息
					ArrayList<HashMap<String,Object>> expoList = enterInvoiceMapper.getExpoList(list.get(0).get("head_id").toString());
					if(!expoList.isEmpty()){
						list.get(0).put("expo",expoList.get(0));
					}
				 }else if(type.equals("T_INV")){//获取运输发票信息
					 ArrayList<HashMap<String,Object>> transList = enterInvoiceMapper.getTransList(list.get(0).get("head_id").toString());
						if(!transList.isEmpty()){
							list.get(0).put("trans",transList.get(0));
						}
				 }
			}
			return list;	 
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
		
	}
	
	/*
	 * 获取单据信息个数
	 */
	@Override
	public int getInvoiceMainListCount(HashMap<String,Object> param){
		return enterInvoiceMapper.getInvoiceMainListCount(param);	
	}
	
	/*
	 * 更新head表
	 */
	@Override 
	public int updateInvoiceMain(HashMap<String,Object> param){
		try{
			Invoice invoice = (Invoice)param.get("invoiceObj");
			Exp exp = (Exp)param.get("expObj");
			Transport trans = (Transport)param.get("transObj");
			enterInvoiceMapper.updateInvoiceMain(invoice);
			if(invoice.getType().equals("E_INV")){//进出口发票
				int idCount = enterInvoiceMapper.getHeadIdFromExp(invoice.getHeadId());
				if(idCount>0){
			    	enterInvoiceMapper.updateInvoiceExp(exp);
				}else{
					enterInvoiceMapper.insertInvoiceExp(exp);
				}
			}else if(invoice.getType().equals("T_INV")){//运输类发票
				int idCount = enterInvoiceMapper.getHeadIdFromTrans(invoice.getHeadId());
				if(idCount>0){
			    	enterInvoiceMapper.updateInvoiceTrans(trans);
				}else{
					enterInvoiceMapper.insertInvoiceTrans(trans);
				}
			}
			return 0;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return -1;
		}
	}
	
	/*
	 * 添加head表
	 */
	@Override 
	public int insertInvoiceMain(HashMap<String,Object> param){
		try{
			Invoice invoice  = (Invoice)param.get("invoiceObj");
			
			// 获取默认客户id
			HashMap<String, Object> cust = new HashMap<String, Object>();
			cust.put("cust_code", invoice.getCustCode());
			cust.put("company_id", param.get("companyId"));
			cust.put("group_id", invoice.getGroupId());
			int cust_id = enterInvoiceMapper.getCustIdForInput(cust);
			// 获取默认联系人id
			String contact_id = enterInvoiceMapper.getContactIdForInput(cust);
			// 获取默认快递公司
			String exp_id = enterInvoiceMapper.getExpressCpnIdForInput(cust);
			invoice.setCust_id(cust_id);
			if (!Tools.isEmpty(contact_id)) {
				invoice.setContactId(Integer.parseInt(contact_id));
			}
			if (!Tools.isEmpty(exp_id)) {
				invoice.setExpress_type(Integer.parseInt(exp_id));
			}
			
 			enterInvoiceMapper.insertInvoiceMain(invoice);
 			Integer maxId = enterInvoiceMapper.getInvoiceMainId(param);//获取当前head表中主键id最大值
 			invoice.setHeadId(maxId);
 			Exp exp = (Exp)param.get("expObj");
 			Transport trans = (Transport)param.get("transObj");
 			exp.setHeadId(maxId);
 			trans.setHeadId(maxId);
 	 		if(invoice.getType().equals("E_INV")){//进出口发票
					enterInvoiceMapper.insertInvoiceExp(exp);
 	 		}else if(invoice.getType().equals("T_INV")){//运输类发票
 	 			    enterInvoiceMapper.insertInvoiceTrans(trans);
 	 		}
			return 0;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return -1;
		}
	}
	
	
	/*
	 * 保存detail信息
	 */
	public int saveInvoiceDetail(HashMap<String,Object> param){
		//添加的记录
		try{List<HashMap<String,Object>> addList = (List<HashMap<String,Object>>)param.get("addList");
		if(addList!=null&&addList.size()>0)
		{
			List<HashMap<String, Object>> subAddList = new ArrayList<HashMap<String, Object>>();
			for(int i = 0; i < addList.size(); ++i)
			{
				subAddList.add(addList.get(i));
				if(subAddList.size() == 5)
				{
					param.put("addList", subAddList);
					enterInvoiceMapper.insertInvoiceDetail(param);
					subAddList.clear();
				}
			}				
			if(subAddList.size() > 0)
			{
				param.put("addList", subAddList);
				enterInvoiceMapper.insertInvoiceDetail(param);
			}
		} 
		//更新的记录
		List<HashMap<String,Object>> updateList = (List<HashMap<String,Object>>)param.get("updateList");
		if(updateList!=null&&updateList.size()>0)
		{
			List<HashMap<String, Object>> subUpdateList = new ArrayList<HashMap<String, Object>>();
			for(int i = 0; i < updateList.size(); ++i)
			{
				subUpdateList.add(updateList.get(i));
				if(subUpdateList.size() == 5)
				{
					param.put("updateList", subUpdateList);
					enterInvoiceMapper.updateInvoiceDetail(param);
					subUpdateList.clear();
				}
			}
			
			if(subUpdateList.size() > 0)
			{
				param.put("updateList", subUpdateList);
				enterInvoiceMapper.updateInvoiceDetail(param);
			}
		}
		//删除的记录
		List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
		if(!Tools.isEmpty(param.get("itemIds").toString())){
			String[] ids = param.get("itemIds").toString().split(",");	
			if(ids.length > 0){
				HashMap<String,String> map= new HashMap<String,String>();
				for(int i=0;i<ids.length;i++){
					map = new HashMap<String,String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				enterInvoiceMapper.deleteInvoiceDetail(param);
			}
		}
			return 0;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return -1;
		}
	}
	
	@Override
	public int deleteInvoiceMain(HashMap<String,Object> param){
		try{
			enterInvoiceMapper.deleteInvoiceMain(param);
			enterInvoiceMapper.deleteInvoiceExp(param);
			enterInvoiceMapper.deleteInvoiceTrans(param);
			ArrayList<HashMap<String,Object>> idList = enterInvoiceMapper.getDetailIdsForDelete(param);			
			if(!idList.isEmpty()){
				HashMap<String,Object> temp = new HashMap<String,Object>();
				temp.put("idList",idList);
				enterInvoiceMapper.deleteInvoiceDetailFromNo(temp);
				enterInvoiceMapper.deleteTransDetail(temp);
			}
			return 0;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return -1;
		}
	}
	
	@Override
	public ArrayList<HashMap<String,Object>> getInvoiceType(HashMap<String,Object> param){
		try{
			return enterInvoiceMapper.getInvoiceType(param);
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}
	
	@Override
	public ArrayList<HashMap<String,Object>> getInvoiceType2(HashMap<String,Object> param){
		try{
			return enterInvoiceMapper.getInvoiceType2(param);
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}
	
	@Override
	public ArrayList<HashMap<String,Object>> getClientInfoForEnter(HashMap<String,Object> param){
		try{
			return enterInvoiceMapper.getClientInfoForEnter(param);
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}

	@Override
	public ArrayList<HashMap<String,Object>> getGoodsInfoForEnter(HashMap<String,Object> param){
		try{
			return enterInvoiceMapper.getGoodsInfoForEnter(param);
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}
	
	
	@Override
	public ArrayList<HashMap<String,Object>> getSellerInfoForEnter(HashMap<String,Object> param){
		try{
			return enterInvoiceMapper.getSellerInfoForEnter(param);
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return null;
		}
	}

	@Override
	public Long getStartFromId(HashMap<String,Object> param) {
		try{
			ArrayList<HashMap<String,Object>> result = enterInvoiceMapper.getStartFromId(param);
			Long rn = (Long)result.get(0).get("rn");
			return rn;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return (long) 1;
		}
	}

	@Override
	public int checkSplitOrMerge(HashMap<String, Object> param) {
		try{
			int count = enterInvoiceMapper.checkSplitOrMerge(param);
			return count;
		}catch(Exception ex){
			logger.error(ex.getMessage());
			return -1;
		}
	}

	@Override
	public String getDocForRule() {
		// TODO Auto-generated method stub
		return enterInvoiceMapper.getDocForRule();
	}

	@Override
	public ArrayList<HashMap<String, Object>> getRuleSet(String companyId) {
		// TODO Auto-generated method stub
		return enterInvoiceMapper.getRuleSet(companyId);
	}

	// 验证当前录入票据客户是否为已维护客户
	@Override
	public HashMap<String, Object> getCustCount(HashMap<String, Object> paramforcust) {
		// TODO Auto-generated method stub
		return enterInvoiceMapper.getCustCount(paramforcust);
	}

	@Override
	public ArrayList<HashMap<String, Object>> getCustCodeForNew() {
		// TODO Auto-generated method stub
		return enterInvoiceMapper.getCustCodeForNew();
	}

	@Override
	public void insertCustData(HashMap<String, Object> paramForNewCust) {
		// TODO Auto-generated method stub
		enterInvoiceMapper.insertCustData(paramForNewCust);
	}

	@Override
	public int getMaxHeadId(HashMap<String, Object> param) {
		// TODO Auto-generated method stub
		return enterInvoiceMapper.getInvoiceMainId(param);
	}

	@Override
	public HashMap<String, Object> getCustForInput(
			HashMap<String, Object> paramForCount) {
		// TODO Auto-generated method stub
		return enterInvoiceMapper.getCustForInput(paramForCount);
	}
}
